
import type { API } from '../../types/typeings';
import request from '../../utils/request';


type ApiResponse<T = any> = API.ApiResponse<T>;
type UserInfo = API.UserInfo;

// 认证相关API
export const authApi = {
  // 登录
  login: (username: string, password: string) => {
    return request.post<ApiResponse<{ token: string; user: UserInfo }>>('/auth/login', { username, password });
  },
  
  // 登出
  logout: () => {
    return request.post('/auth/logout');
  },
  
  // 刷新token
  refreshToken: () => {
    return request.post('/auth/refresh');
  },

  // 保存用户信息到本地存储
  saveUserInfo: (token: string, user: UserInfo) => {
    // 设置过期时间：当前时间 + 24小时
    const expireTime = Date.now() + 24 * 60 * 60 * 1000;
    const userInfo = { ...user, token, expireTime };
    localStorage.setItem('user', JSON.stringify(userInfo));
    localStorage.setItem('token', token);
    return userInfo;
  },

  // 从本地存储获取用户信息
  getUserInfo: (): UserInfo | null => {
    const userStr = localStorage.getItem('user');
    if (userStr) {
      try {
        const userInfo: UserInfo = JSON.parse(userStr);
        // 检查是否过期
        if (userInfo.expireTime && userInfo.expireTime > Date.now()) {
          return userInfo;
        } else {
          // 已过期，清除
          authApi.clearUserInfo();
        }
      } catch (error) {
        console.error('解析用户信息失败:', error);
      }
    }
    return null;
  },

  // 清除用户信息
  clearUserInfo: () => {
    localStorage.removeItem('user');
    localStorage.removeItem('token');
  }
};





export const login = async (username: string, password: string) : Promise<any> => {
  const response  = await request.post("/api/login", { username, password });

  return response;
}


export const getUserInfo = async () : Promise<any> => {
  const response  = await request.post("/api/user/info");

  return response;
}



export const logout = async () : Promise<any> => {
  const response  = await request.post("/api/logout");

  return response;
}